#include "Session.h"
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

Session::Session(boost::asio::io_context& ioc, Server* server) : m_socket{ ioc }, m_server{ server }
{
	auto uuid = boost::uuids::random_generator()();
	m_uuid = boost::uuids::to_string(uuid);
}

tcp::socket& Session::Socket()
{
	return m_socket;
}

void Session::Start()
{
	memset(m_data, 0, MAX_LENGTH);
	m_socket.async_read_some(boost::asio::buffer(m_data, MAX_LENGTH),
		std::bind(&Session::handle_read, this, std::placeholders::_1, std::placeholders::_2, shared_from_this())
	);
}

void Session::handle_read(const boost::system::error_code& error, size_t bytes_transferred, std::shared_ptr<Session> _self_session)
{
	if (!error) {
		std::cout << "server recevice data is : " << m_data << std::endl;
		boost::asio::async_write(m_socket, boost::asio::buffer(m_data, bytes_transferred),
			std::bind(&Session::handle_write, this, std::placeholders::_1, _self_session)
		);
	}
	else {
		std::cout << error.message() << std::endl;
		m_server->cleanSession(m_uuid);
	}
}

void Session::handle_write(const boost::system::error_code& error, std::shared_ptr<Session> _self_session) {
	if (!error) {
		memset(m_data, 0, MAX_LENGTH);
		m_socket.async_read_some(boost::asio::buffer(m_data, MAX_LENGTH),
			std::bind(&Session::handle_read, this, std::placeholders::_1, std::placeholders::_2, _self_session)
		);
	}
	else {
		std::cout << error.message() << std::endl;
		//delete this;
		m_server->cleanSession(m_uuid);
	}
}